<template>
  <view>
    <view
      v-for="item in goodsList"
      :key="item.goods_id"
      @click="goToGoodsDetail(item)"
    >
      <my-goods :goods="item" />
    </view>
  </view>
</template>

<script>
import { request } from '@/utils/request'
import MyGoods from '@/components/my-goods'
export default {
  components: {
    MyGoods
  },
  data () {
    return {
      // 请求参数对象
      queryObj: {
        // 查询关键字
        query: '',
        // 商品分类id
        cid: '',
        // 页码值
        pagenum: 1,
        // 每页显示多少条数据
        pagesize: 10
      },
      // 商品列表的数据
      goodsList: [],
      // 总数量，用来实现分页
      total: 0,
      isLoading: false
    }
  },
  onPullDownRefresh () {
    this.goodsList = []
    this.queryObj.pagenum = 1
    this.total = 0
    this.isLoading = false

    this.getGoodsList(() => {
      uni.stopPullDownRefresh()
    })
  },
  // 上拉加载更多
  onReachBottom () {
    // 判断是否还有数据
    if (this.queryObj.pagenum * this.queryObj.pagesize >= this.total) {
      uni.showToast({
        title: '没有数据啦...',
        icon: 'none',
        duration: 1000
      })
      return
    }

    // 判断是否正在加载
    if (this.isLoading) return

    this.queryObj.pagenum += 1
    this.getGoodsList()
  },
  onLoad (options) {
    // 将页面参数，转存到 this.queryObj 对象中
    this.queryObj.query = options.query || ''
    this.queryObj.cid = options.cid || ''

    // 调用获取商品列表数据的方法
    this.getGoodsList()
  },
  methods: {
    async getGoodsList (cb) {
      this.isLoading = true
      const res = await request({
        url: '/api/public/v1/goods/search',
        data: this.queryObj
      })
      this.isLoading = false
      cb && cb()
      if (res.meta.status === 200) {
        this.goodsList = [...this.goodsList, ...res.message.goods]
        this.total = res.message.total
      }
    },
    // 跳转到商品详情
    goToGoodsDetail (goods) {
      uni.navigateTo({
        url: '/subpkg/goods_detail/index?goods_id=' + goods.goods_id
      })
    }
  }
}
</script>
